package com.example.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.app.MyApplication;
import com.example.tool.BaseActivity;
import com.example.tool.Config;
import com.example.tool.Utils;
import com.example.utils.WifiConnector;
import com.example.version.UpdateManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class LoginActivity extends BaseActivity implements WifiConnector.CallBack{
    private EditText et_user, et_pwd;
    private TextView tv_commit, title_tv, tv_right_btn;
    private String userurl = MyApplication.SERVERPATH + "/Y502/Pad2Login";
    private String username, password;
    RequestQueue mQueue = null;
    JsonObjectRequest mJsonObjectRequest = null;
    String riqi = "";
    private String linename, sn, renshu, k1, k2, k3, j1, j2, j3, mbcl, mbpph;
	private String k1_2, k2_2, j1_2, j2_2, k1_3, k2_3, j1_3, j2_3;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    private String TAG = "LoginActivity";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        userurl = MyApplication.SERVERPATH + "/Y502/Pad2Login";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        String sta = MyApplication.yy;
        updateActivity(sta, LoginActivity.class);

        setContentView(R.layout.activity_login);
        //	MyApplication.mylist.add(this);
        mQueue = MyApplication.getRequestQueue();
        username = MyApplication.getSharedUserInfo().getString("username", "admin");
        password = MyApplication.getSharedUserInfo().getString("password", "123");
        riqi = MyApplication.getSharedUserInfo().getString("riqi", "");

        initView();
        MyApplication.getSharedUserInfo().edit().putString(Config.ACCESS_TOKEN, "").commit();
        // for(int i=MyApplication.mylist.size()-1;i>=0;i--)
        //		MyApplication.mylist.get(i).finish();
        //apk版本升级
        UpdateManager.getUpdateManager().checkAppUpdate(this, false);

        //连接wifi
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        List<ScanResult> _wifilist;
        _wifilist = wifiManager.getScanResults();
        String wifiApName = "MES1";
        for (ScanResult sr : _wifilist) {
            if (sr.SSID.equals("MES1")) {
                wifiApName = sr.SSID;
                break;
            }
        }
//        WifiConnector.connectWifiApByNameAndPwd(this, wifiApName, "esm38522", this);

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    time++;
                    if (time > 6) {
                        mHandler.sendEmptyMessage(ONMAIN);
                        break;
                    }
                }
            }
        }.start();

    }

    int time = 0;
    public static final int ONMAIN = 1313;//到首页

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (ONMAIN == msg.what) {
                onMain();
            }
        }
    };

    void onMain() {
        if (MyApplication.getServersInfo().getString("serverip", "").equals("")) {
            showToast(getString(R.string.input_ipport));
            return;
        }
        username = et_user.getText().toString();
        if (username.trim().equals("")) {
            showToast(getString(R.string.input_username));
            return;
        }
        password = et_pwd.getText().toString();
        if (password.trim().equals("")) {
            showToast(getString(R.string.input_password));
            return;
        }
        login(username, password);
    }

    private void initView() {
        et_user = (EditText) findViewById(R.id.et_user);
        et_user.setText(username);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_pwd.setTypeface(Typeface.DEFAULT);
        et_pwd.setTransformationMethod(new PasswordTransformationMethod());
        et_pwd.setText(password);
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(R.string.Easement);
        tv_commit = (TextView) findViewById(R.id.tv_commit);
        tv_commit.setOnClickListener(this);
        tv_right_btn = (TextView) findViewById(R.id.tv_right_btn);
        tv_right_btn.setText(R.string.netsetting);
        tv_right_btn.setOnClickListener(this);

        Button bt_deviceset = (Button) findViewById(R.id.bt_deviceset);
        bt_deviceset.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_commit:
                if (MyApplication.getServersInfo().getString("serverip", "").equals("")) {
                    showToast(getString(R.string.input_ipport));
                    return;
                }
                username = et_user.getText().toString();
                if (username.trim().equals("")) {
                    showToast(getString(R.string.input_username));
                    return;
                }
                password = et_pwd.getText().toString();
                if (password.trim().equals("")) {
                    showToast(getString(R.string.input_password));
                    return;
                }
                login(username, password);
                break;
            case R.id.tv_right_btn:
                time = -999999;
                startActivity(new Intent(this, NetSettingActivity.class));
                break;
            case R.id.bt_deviceset:
                time = -999999;
                startActivity(new Intent(this, DeviceSettingActivity.class));
                break;
            default:
                break;
        }
    }

    private void login(String name, String pass) {

        boolean isConnected = Utils.toastIsNetworkConnected(context);
        if (isConnected) {
            showProgressBar();
            String url = userurl + "?name=" + name + "&&pass=" + pass + "&&type=1";
            //RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
            mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url,
                    null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    hideProgressBar();
                    parseData(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    hideProgressBar();
                    showToast(getString(R.string.network_error_try_again));
                }
            }
            );
            mQueue.add(mJsonObjectRequest);
        } else {
            showToast(getString(R.string.network_error_try_again));
            return;
        }
    }

    @Override
    protected void onDestroy() {
//	MyApplication.mylist.remove(this);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void parseData(JSONObject response) {

        String access_token = "access_token";
        String result = response.optString("result");
        if (result == null || result.equals("") || result.equals("fail")) {
            MyApplication.getSharedUserInfo().edit().putString(Config.ACCESS_TOKEN, "").commit();
            MyApplication.getSharedUserInfo().edit().putString("password", "").commit();
            showToast(R.string.login_error);
            return;
        }
        MyApplication.getSharedUserInfo().edit().putString(Config.ACCESS_TOKEN, access_token).commit();
        MyApplication.getSharedUserInfo().edit().putString("username", username).commit();
        MyApplication.getSharedUserInfo().edit().putString("password", password).commit();
        JSONArray array = response.optJSONArray("data");
        if (array != null) {
            JSONObject obj = array.optJSONObject(0);  // linename,sn,renshu,k1,k2,k3,j1,j2,j3;
            linename = obj.optString("linename");
            sn = obj.optString("sn");
            renshu = obj.optString("renshu");
            k1 = obj.optString("k1");
            k2 = obj.optString("k2");
            k3 = obj.optString("k3");
            j1 = obj.optString("j1");
            j2 = obj.optString("j2");
            j3 = obj.optString("j3");
            mbcl = obj.optString("mbcl");
            mbpph = obj.optString("mbpph");

			k1_2 = obj.optString("k1_2");
			k2_2 = obj.optString("k2_2");
			j1_2 = obj.optString("j1_2");
			j2_2 = obj.optString("j2_2");

			k1_3 = obj.optString("k1_3");
			k2_3 = obj.optString("k2_3");
			j1_3 = obj.optString("j1_3");
			j2_3 = obj.optString("j2_3");
        }

        Long stime = response.optLong("time", 0);

        if (stime > 0) {
            long now = System.currentTimeMillis() / 1000; //当前时间
            long xtime = stime - now;
            if (xtime > 60 || xtime < -60) {
                MyApplication.xtime = xtime;
            }
        }

        long thistime = MyApplication.xtime * 1000 + System.currentTimeMillis();
        String riqi1 = df.format(new Date(thistime));
        if (!riqi1.equals(riqi)) {
            MyApplication.getSharedUserInfo().edit().putString("nnn", "0").commit();
            MyApplication.getSharedUserInfo().edit().putString("riqi", riqi1).commit();
        }
        
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("sn", sn);
        intent.putExtra("chanxian", linename);
        intent.putExtra("renshu", renshu);
        intent.putExtra("k1", k1);
        intent.putExtra("k2", k2);
        intent.putExtra("k3", k3);
        intent.putExtra("j1", j1);
        intent.putExtra("j2", j2);
        intent.putExtra("j3", j3);
        intent.putExtra("mbcl", mbcl);
        intent.putExtra("mbpph", mbpph);

		intent.putExtra("k1_2", k1_2);
		intent.putExtra("k2_2", k2_2);
		intent.putExtra("j1_2", j1_2);
		intent.putExtra("j2_2", j2_2);

		intent.putExtra("k1_3", k1_3);
		intent.putExtra("k2_3", k2_3);
		intent.putExtra("j1_3", j1_3);
		intent.putExtra("j2_3", j2_3);

        startActivity(intent);
        finish();
    }

    @Override
    public void connnectResult(boolean connectResult) {
        if (connectResult) {
            String url = userurl + "?name=admin&&pass=123&&type=1";
            mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url,
                    null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    showToast("已连接成功！");
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    System.out.println("xxx");
                    showToast("没有连接成功！");
                }
            }
            );
            mQueue.add(mJsonObjectRequest);
        }

    }

}
